//权限文件
//引入仓库
import store from '@/store'
//引入路由
import router from '@/router'

//引入进度条
import NProgress from 'nprogress'
NProgress.configure({showSpinner: false}) // NProgress Configuration
import 'nprogress/nprogress.css'
//跳转白名单
let whiteList = ['/login', '/404']

//路由前置守卫
router.beforeEach(async (to, from, next) => {
  //开启进度条
  NProgress.start()

  //获取token
  const token = store.getters.token

  if (!!token) {
    //去不去登录页面
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      //有没有用户信息
      const isGetUserInfo = store.getters.isGetUserInfo

      //如果有用户信息 直接放行
      if (isGetUserInfo) {
        next()
      } else {
        //尝试获取用户信息
        try {
          //获取用户信息
          await store.dispatch('user/A_getUserInfo')
          //拿到角色
          const role = store.state.user.role
          //获取可以被循环添加的动态路由
          let accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            role
          )
          //循环添加动态路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })

          //设置用户状态为true
          store.commit('permission/SET_USERINFO_STATE', true)

          //hack方法 无线向下跳转 保证路由添加成功
          //replace true 路由历史栈里面不会保存路由 为了防止后退
          next({...to, replace: true})
        } catch (error) {
          //等待清空用户信息
          await store.dispatch('user/A_clear')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    //去不去白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      //跳转到登录页面 携带去的地址
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

//路由后置守卫
router.afterEach(() => {
  //关闭进度条
  NProgress.done()
})
